package com.jwm.power.controller;

import cn.dev33.satoken.stp.StpUtil;
import cn.zhxu.bs.MapSearcher;
import cn.zhxu.bs.util.MapUtils;
import com.jwm.power.mapper.QueryMapper;
import com.jwm.power.model.entity.Depts;
import com.jwm.power.model.entity.Menus;
import com.jwm.power.model.entity.Users;
import com.jwm.power.model.reponse.ResponseData;
import com.jwm.power.service.DeptsService;
import com.jwm.power.util.Ut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

//  部门管理
@Controller
@RequestMapping("/depts")
public class DeptsController {

    @Autowired
    private DeptsService deptsService;
    @Autowired
    private MapSearcher mapSearcher;              // 注入 BeanSearcher 的检索器
    @Autowired
    private QueryMapper queryMapper;

    //  获取部门数据
    @RequestMapping(value = "/queryDepts", method = RequestMethod.GET)
    public void QueryDepts(HttpServletRequest request, HttpServletResponse response) {
        try {
            Users users = (Users) StpUtil.getSession().get("users");
            // 一行代码，实现一个用户检索接口（MapUtils.flat 只是收集前端的请求参数）
            String deptName = request.getParameter("sName");
            List<Map<String, Object>> searchResult = new ArrayList<>();
            if (deptName.length() > 0) {
                Map<String, Object> objectMap = new HashMap<>();
                objectMap.put("strCell", "distinct deptid, deptname, parentcode, deptcode, parentdeptid, remarks,sn");
                objectMap.put("strChildCell", "c.deptid, c.deptname, c.parentcode, c.deptcode, c.parentdeptid, c.remarks,c.sn");
                objectMap.put("strWhere", " deptname like '%" + deptName + "%'");
                objectMap.put("tName", " Depts");
                objectMap.put("strChildWhere", " t.deptcode = c.parentcode");
                searchResult = queryMapper.queryWithDatas(objectMap);
            } else {
                List<String> cellList = new ArrayList<>();
                if (!users.getUsername().equals("admin")) {
                    Map<String, Object> objectMap = new HashMap<>();
                    objectMap.put("tName", "Depts d");
                    objectMap.put("strCell", "d.deptcode");
                    String strWhere = " left join UserDepts u on u.deptcode = d.deptcode ";
                    strWhere += " where u.userid=" + users.getUserid();
                    objectMap.put("strWhere", strWhere);
                    cellList = queryMapper.queryCellDatas(objectMap);
                    if (cellList.size() == 0) {
                        cellList.add(users.getDeptcode());
                    }
                }
                Map<String, Object> params = MapUtils.builder()
                        .field("deptcode", cellList).op("il")
                        .build();
                searchResult = mapSearcher.searchAll(Depts.class, params);
            }
            Map<String, Object> dataMap = new HashMap<>();
            List<Map<String, Object>> treeMap = new ArrayList<>();
            //  重新组装树形数据
            for (Map<String, Object> objectMap : searchResult) {
                Integer isParent = 0;
                for (Map<String, Object> checkMap : searchResult) {
                    if (checkMap.get("deptcode").equals(objectMap.get("parentcode"))) {
                        isParent = 1;
                    }
                }
                if (isParent == 0) {
                    Map<String, Object> itemMap = Ut.loadTreeData(objectMap, searchResult, "deptcode");
                    treeMap.add(itemMap);
                }
            }
            dataMap.put("data", treeMap);
            Ut.toJson(response, dataMap);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //  加载左侧树形菜单
    @RequestMapping(value = "/queryTreeJs", method = RequestMethod.GET)
    public void QueryTreeJs(HttpServletRequest request, HttpServletResponse response) {
        try {
            // 一行代码，实现一个用户检索接口（MapUtils.flat 只是收集前端的请求参数）
            Users users = (Users) StpUtil.getSession().get("users");
            List<String> cellList = new ArrayList<>();
            if (!users.getUsername().equals("admin")) {
                Map<String, Object> objectMap = new HashMap<>();
                objectMap.put("tName", "Depts d");
                objectMap.put("strCell", "d.deptcode");
                String strWhere = " left join UserDepts u on u.deptcode = d.deptcode ";
                strWhere += " where u.userid=" + users.getUserid();
                objectMap.put("strWhere", strWhere);
                cellList = queryMapper.queryCellDatas(objectMap);
                if (cellList.size() == 0) {
                    cellList.add(users.getDeptcode());
                }
            }
            Map<String, Object> params = MapUtils.builder()
                    .field("deptcode", cellList).op("il")
                    .build();
            List<Map<String, Object>> searchResult = mapSearcher.searchAll(Depts.class, params);
            List<Map<String, Object>> treeMap = new ArrayList<>();
            //  重新组装树形数据
            Integer index = 0;
            for (Map<String, Object> objectMap : searchResult) {
                if (objectMap.get("parentcode").equals("00")) {
                    Map<String, Object> itemMap = new HashMap<>();
                    Map<String, Object> treeStatus = new HashMap<>();
                    treeStatus.put("opened", true);
                    if (index == 0) {
                        treeStatus.put("selected", true);
                    }
                    for (String mapKey : objectMap.keySet()) {
                        switch (mapKey) {
                            case "deptname":
                                itemMap.put("text", objectMap.get(mapKey));
                                break;
                            default:
                                itemMap.put(mapKey, objectMap.get(mapKey));
                                break;
                        }
                    }
                    itemMap.put("state", treeStatus);  //  加载子集
                    itemMap.put("children", loadTreejsChilds(searchResult, itemMap));  //  加载子集
                    treeMap.add(itemMap);
                    index++;
                }
            }
            Ut.toJson(response, treeMap);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public List<Map<String, Object>> loadTreejsChilds(List<Map<String, Object>> dataMaps, Map<String, Object> dataMap) {
        List<Map<String, Object>> mapList = new ArrayList<>();
        for (Map<String, Object> objectMap : dataMaps) {
            if (objectMap.get("parentcode").equals(dataMap.get("deptcode").toString())) {
                Map<String, Object> itemMap = new HashMap<>();
                for (String mapKey : objectMap.keySet()) {
                    switch (mapKey) {
                        case "deptname":
                            itemMap.put("text", objectMap.get(mapKey));
                            break;
                        default:
                            itemMap.put(mapKey, objectMap.get(mapKey));
                            break;
                    }
                }
                itemMap.put("children", loadTreejsChilds(dataMaps, objectMap));  //  加载子集
                mapList.add(itemMap);
            }
        }
        return mapList;
    }

    //  设置部门
    @RequestMapping(value = "saveDepts", method = RequestMethod.POST)
    @ResponseBody
    public ResponseData SaveDepts(HttpServletRequest request, HttpServletResponse response) throws ParseException {
        return deptsService.SaveDepts(request);
    }

}
